app.controller('shopDeliveryAddCtrl', ['$scope', '$state', '$cookies', '$modal', 'shopDeliveryAddService', 'utilService', 'toaster', function ($scope, $state, $cookies, $modal, shopDeliveryAddService, utilService, toaster) {

    $scope.shopDelivery = {};
    $scope.type = null;
    $scope.vehicle = null;

    $scope.insert = function () {
        if($scope.shopDelivery.minDelivery > $scope.shopDelivery.maxDelivery){
            toaster.pop('error', "操作失败", "最大配送距离必须大于最小配送距离");
            return;
        }
        shopDeliveryAddService.insert($scope).then(function (result) {
            switch (result.status) {
                case 200:
                    toaster.pop('success', "提示", "操作成功");
                    $state.go('app.shopDelivery');
                    break;
                default:
                    toaster.pop('error', "操作失败", "发生未知错误！请联系管理员");
                    break;
            }
        });
    }

    $scope.$watch("shopDelivery.vehicle", function(n, o){
        if(n!=undefined){
            $scope.vehicle = parseInt(n);
            if($scope.shopDelivery.type!=undefined){
                shopDeliveryAddService.adapt($scope).then(function (result) {
                    switch (result.status) {
                        case 200:
                            if(result.data!=null){
                                $scope.shopDelivery.minDelivery = result.data.maxDelivery;
                            }else{
                                $scope.shopDelivery.minDelivery = 0;
                            }
                            break;
                        default:
                            $scope.shopDelivery.minDelivery = 0;
                            break;
                    }
                });
            }
        }
    },true);

    $scope.$watch("shopDelivery.type", function(n, o){
        if(n!=undefined){
            $scope.type = parseInt(n);
            if($scope.shopDelivery.vehicle!=undefined){
                shopDeliveryAddService.adapt($scope).then(function (result) {
                    switch (result.status) {
                        case 200:
                            if(result.data!=null){
                                $scope.shopDelivery.minDelivery = result.data.maxDelivery;
                            }else{
                                $scope.shopDelivery.minDelivery = 0;
                            }
                            break;
                        default:
                            $scope.shopDelivery.minDelivery = 0;
                            break;
                    }
                });
            }
        }
    },true);

}]);
